package mwa.cs.sm.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.MeterBrandDAO;
import mwa.cs.dao.ReaderDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.database.Database;
import mwa.cs.model.Reader;
import mwa.cs.util.JDate;

/**
 * Servlet implementation class CS12001Srvl
 */
public class CS12001Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
	private Database db;
	private String vaAgentBrowser;
	private String vaUrlAddress;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS12001Srvl() {
        super();
        
    }
    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	String vaProcessType = request.getParameter("process_type");
    	vaUrlAddress = request.getParameter("url_address");
    	vaAgentBrowser = request.getParameter("agent_browser");
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		if(vaProcessType.equals("insert")){ 
			insert(request,response);	
		} else if(vaProcessType.equals("edit")){ 
			edit(request , response);
		}else if(vaProcessType.equals("delete")){
			delete(request,response);
		}else if(vaProcessType.equals("update")) {
			update(request,response);
		}else{
			getDataTable(request,response);
		}
    }
    public void delete(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		int vnReadeId = Integer.parseInt(request.getParameter("id"));
		ReaderDAO voReaderDAO = new ReaderDAO(db);
		try {
			db.beginTransaction();
			voReaderDAO.deleteReaderBySiteId(vnSiteId, vnReadeId);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS12001", JDate.getDate(), JDate.getTime(),vnUserId, "CS12001Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		} finally {
			db.close();
		}
		response.getWriter().write("success");
    	
    }
    public void update(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		int vnReadeId = Integer.parseInt(request.getParameter("id"));
		String vaReaderName = request.getParameter("name");
		String vaStatus = request.getParameter("status");
		int vnOldReaderId = Integer.parseInt(request.getParameter("oldCodeID"));
		ReaderDAO voReaderDAO = new ReaderDAO(db);
		
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();
    	String vaCheckId = voReaderDAO.findsReaderIdBySiteAndReader(vnSiteId, vnOldReaderId, vnReadeId);
    	if(vaCheckId == null){
    		Reader poReader = new Reader();
    		poReader.setVnSiteId(vnSiteId);
    		poReader.setVnReaderId(vnReadeId);
    		poReader.setVaReaderName(vaReaderName);
    		poReader.setVaStatus(vaStatus);
    		poReader.setVnUpdateUserId(vnUserId);
    		poReader.setvaUpdateDate(vaDate);
    		poReader.setVaUpdateTime(vaTime);
    		try {
    			db.beginTransaction();
        		voReaderDAO.updateReader(vnSiteId, vnOldReaderId, poReader);
        		db.commit();
    		} catch (Exception e) {
    			SMErrorLogDAO.getInstance().addLog(0, "CS12001", JDate.getDate(), JDate.getTime(),vnUserId, "CS12001Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
    			db.rollback();
    			e.getMessage();
    		} finally{
    			db.close();
    		}
    		response.getWriter().write("update_Success");
    		
    	}else{
    		db.close();
    		response.getWriter().write("ReaderId_Dupicate");
    	}
    }
    public void insert(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		int vnReadeId = Integer.parseInt(request.getParameter("id"));
		String vaReaderName = request.getParameter("name");
		String vaStatus = request.getParameter("status");
		ReaderDAO voReaderDAO = new ReaderDAO(db);
		
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();
		String vaCheckId = voReaderDAO.findReaderIdBySiteAndReader(vnSiteId,vnReadeId);
		
		if(vaCheckId == null){
				Reader voReader = new Reader();
				voReader.setVnSiteId(vnSiteId);
				voReader.setVnReaderId(vnReadeId);
				voReader.setVaReaderName(vaReaderName);
				voReader.setVaStatus(vaStatus);
				voReader.setVaInsertUserId(vnUserId);
				voReader.setVaInsertDate(vaDate);
				voReader.setVaInsertTime(vaTime);
				try {
					db.beginTransaction();
					voReaderDAO.addReader(voReader);
					db.commit();
				} catch (Exception e) {
					SMErrorLogDAO.getInstance().addLog(0, "CS12001", JDate.getDate(), JDate.getTime(),vnUserId, "CS12001Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
					db.rollback();
					e.getMessage();
				} finally{
					db.close();
				}
				response.getWriter().write("insert_success");
		}else{
			db.close();
			response.getWriter().write("ReaderId_Dupicate");
		}
    	
    }
    public void edit(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		JSONObject voObject  = new JSONObject();
		String vaReaderId = request.getParameter("id");
		ReaderDAO voReaderDAO = new ReaderDAO(db);
		
		voObject.put("id",vaReaderId );
		voObject.put("name",voReaderDAO.findReaderNameBySiteAndReaderId(vnSiteId, vaReaderId,"READER_NAME"));
		voObject.put("status",voReaderDAO.findReaderNameBySiteAndReaderId(vnSiteId, vaReaderId, "STATUS"));
		PrintWriter voOut = response.getWriter();
		
		db.close();
		voOut.print(voObject.toJSONString());
    	
    }
    public void getDataTable(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter voOut = response.getWriter();
		
		this.db = new Database();
		ReaderDAO voReaderDAO = new ReaderDAO(db);
		List<Map<String , Object>> voListFindAll;
		voListFindAll = voReaderDAO.findsReaderBySite(vnSiteId);
	
		for(int i = 0; i < voListFindAll.size() ; i++){ 
			Map<String , Object> voMapItem = (Map<String , Object>) voListFindAll.get(i);
			voColumn = new JSONArray();
			voColumn.add(i+1);
			voColumn.add(voMapItem.get("READER_ID"));
			voColumn.add(voMapItem.get("READER_NAME"));
			voColumn.add(voMapItem.get("STATUS"));
			voRow.add(voColumn);
		}
			voObject.put("iTotalRecords", voListFindAll.size());
			voObject.put("iTotalDisplayRecords", voListFindAll.size());
			voObject.put("aaData", voRow);
		
		db.close();
		 voOut.print(voObject.toJSONString());
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
